package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.HotServeListDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author SumJane
 * @since 2025-08-28
 */
@RequiredArgsConstructor
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    private final ServeItemMapper serveItemMapper;
    private final RegionMapper regionMapper;
    private final ServeMapper serveMapper;

    /***
     *删除服务列表*/
    @Override
    public void myRemoveById(Long id) {
        boolean remove = remove(Wrappers.<Serve>lambdaQuery().eq(Serve::getId, id).eq(Serve::getSaleStatus, FoundationStatusEnum.INIT.getStatus()));
        if (!remove) {
            throw new ForbiddenOperationException("服务无法删除");
        }
    }

    /**
     * 服务下架
     */
    @CacheEvict(value = RedisConstants.CacheName.SERVE,key = "#id")
    @Override
    public Serve offSale(Long id) {
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("服务下架失败");
        }
        return null;
    }

    /**
     * 更新服务为热门
     *
     * @return
     */
    @CachePut(value = RedisConstants.CacheName.SERVE,key = "#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Override
    public Serve onHot(Long id) {
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, 1).update();
        if (!update) {
            throw new ForbiddenOperationException("更新服务为热门失败");
        }
        return getById(id);
    }

    /**
     * 更新服务为非热门
     */
    @Override
    public void offHot(Long id) {
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, 0).update();
        if (!update) {
            throw new ForbiddenOperationException("更新服务为非热门失败");
        }
    }

    /**
     * 查询区域服务信息
     * */
    @Override
//    TODO @Cacheable(value = RedisConstants.CacheName.SERVE , key = "#id")
    public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }

    /**
     * 首页热门服务列表
     * */
    @Override
    public List<HotServeListDTO> hotServeList(Long regionId) {

        return serveMapper.hotServeList(regionId);
    }

    /***
     * 分页条件查询*/
    @Override
    public PageResult<ServeResDTO> myPage(ServePageQueryReqDTO dto) {
        return PageHelperUtils.selectPage(dto, new PageHelperUtils.QueryExecutor<ServeResDTO>() {
            @Override
            public List<ServeResDTO> query() {
                return baseMapper.myPage(dto.getRegionId());
            }
        });
    }


    /**
     * 上架
     *
     * @return
     */
    @Override
    @Transactional
    public Serve onSale(Long id) {
        Serve serve = getById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //草稿或下架状态方可上架
        if (!(saleStatus==FoundationStatusEnum.INIT.getStatus() || saleStatus==FoundationStatusEnum.DISABLE.getStatus())) {
            throw new ForbiddenOperationException("草稿或下架状态方可上架");
        }
//服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();
        //服务项为启用状态方可上架
        if (!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)) {
            throw new ForbiddenOperationException("服务项为启用状态方可上架");
        }

        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return getById(id);
    }


    /***
     * 修改服务价格
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Serve myUpdateServe(Long id, BigDecimal price) {
        boolean update = lambdaUpdate().eq(Serve::getId, id).eq(Serve::getPrice, price).update();
        if (!update) {
            throw new ForbiddenOperationException("修改服务价格失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTO) {
        serveUpsertReqDTO.forEach(sd -> {
            ServeItem serveItem = serveItemMapper.selectOne(Wrappers.<ServeItem>lambdaQuery()
                    .eq(ServeItem::getId, sd.getServeItemId()));
            if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("该服务未启用或不存在!");
            }
            Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery()
                    .eq(Serve::getRegionId, sd.getRegionId())
                    .eq(Serve::getServeItemId, sd.getServeItemId()));
            if (count > 0) {
                throw new ForbiddenOperationException("0901该服务不能重复添加!");
            }
            Region region = regionMapper.selectOne(Wrappers.<Region>lambdaQuery().eq(Region::getId, sd.getRegionId()));
            if (region == null) {
                throw new ForbiddenOperationException("该服务未开通!");
            }
            Serve serve = BeanUtils.toBean(sd, Serve.class);
            serve.setCityCode(region.getCityCode());
            serve.setPrice(serveItem.getReferencePrice());
            getBaseMapper().insert(serve);
        });
    }

    /***
     * 新增区域服务
     * @param serveUpsertReqDTOS 50条
     */
    @Transactional
    public void batchAddInfo(List<ServeUpsertReqDTO> serveUpsertReqDTOS) {
        //1、查询所有服务
        List<Long> ids = serveUpsertReqDTOS.stream().map(s -> s.getServeItemId()).collect(Collectors.toList());
        List<ServeItem> serveItems = serveItemMapper.selectList(Wrappers.<ServeItem>lambdaQuery().in(ServeItem::getId, ids));
        long count1 = serveItems.stream().filter(si -> si.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()).count();
        if (count1 > 0) {
            throw new ForbiddenOperationException("服务项未启用或不存在！");
        }

        //2.2 当前区域是否已经添加过该服务项
        Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery()
                .in(Serve::getServeItemId, ids)
                .eq(Serve::getRegionId, serveUpsertReqDTOS.get(0).getRegionId()));
        if (count > 0) {
            throw new ForbiddenOperationException("该服务项不能重复添加！");
        }

        //2.3 区域是否存在
        Region region = regionMapper.selectOne(Wrappers.<Region>lambdaQuery().eq(Region::getId, serveUpsertReqDTOS.get(0).getRegionId()));
        if (region == null) {
            throw new ForbiddenOperationException("该区域不存在！");
        }

        List<Serve> list = serveUpsertReqDTOS.stream().map(sur -> {
            Serve serve = BeanUtil.toBean(sur, Serve.class);
            serve.setCityCode(region.getCityCode());
            ServeItem item = serveItems.stream().filter(si -> Objects.equals(sur.getServeItemId(), si.getId())).findFirst().orElse(null);
            assert item != null;
            serve.setPrice(item.getReferencePrice());
            return serve;
        }).collect(Collectors.toList());

        saveBatch(list);
    }


}
